package fyp.spedmew.connector;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

import com.google.api.client.http.HttpStatusCodes;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.InputStream;

import fyp.spedmew.util.Constant;


public class DownloadImageATask extends AsyncTask<String, Void, Bitmap> {
    private static final String TAG = new Object(){}.getClass().getCanonicalName();

    private ImageView bmImage;

    private Bitmap bitmap;

    public DownloadImageATask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    public DownloadImageATask(Bitmap bitmap) {
        this.bitmap = bitmap;
    }

    protected Bitmap doInBackground(String... urls) {
        String key = urls[0];
        String urldisplay = constructURL(key);
        Log.i(TAG, "Download image from " + urldisplay);
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        if (bmImage != null) {
            bmImage.setImageBitmap(result);
        }
        bitmap = result;
    }

    private String constructURL(String key) {
        return "http://" + Constant.APP_ADDRESS + ":" + Constant.APP_PORT + "/serve?key=" + key;
    }
}
